package com.raychi.demo;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.raychi.demo.util.SessionUtil;

public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		String uri = request.getRequestURI();
		// 忽略不用验证的地址
		if (uri.indexOf("/student/student_login.action") >= 0 || uri.indexOf("/student/student_regist.action") >= 0 
				|| uri.indexOf("/teacher/teacher_login.action") >= 0 || uri.indexOf("/student/student_save.action") >= 0 
				|| uri.indexOf("/teacher/teacher_input.action") >= 0 || uri.indexOf("/teacher/teacher_regist.action") >= 0 
				|| uri.indexOf("/teacher/teacher_save.action") >= 0 || uri.indexOf("/user/user_login.action") >= 0 
				|| uri.indexOf("/student/student_input.action") >= 0) {
			chain.doFilter(req, resp);
			return;
		}
		
		HttpSession session = request.getSession(false);
		if (uri.indexOf("/student") >= 0) {
			if (session == null || session.getAttribute(SessionUtil.KEY_SESSION_STUDENT) == null) {
				response.sendRedirect(request.getContextPath() + "/student/student_login.action");
				return;
			}
		} else if (uri.indexOf("/teacher") >= 0) {
			if (session == null || session.getAttribute(SessionUtil.KEY_SESSION_TEACHER) == null) {
				response.sendRedirect(request.getContextPath() + "/teacher/teacher_login.action");
				return;
			}
		} 
		chain.doFilter(req, resp);
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}

}
